package com.ssyc.student.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.student.R;
import com.ssyc.student.adapter.StTreasuerBackgroundAdapter;
import com.ssyc.student.adapter.StTreasuerClothesAdapter;
import com.ssyc.student.bean.SavePetItemJson;
import com.ssyc.student.bean.TreasureChestInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


/**
 * 学生端--百宝箱--时装道具
 */

public class StudentFashionableDressFragment extends LazyBaseFragment implements View.OnClickListener {

    //下拉刷新控件
    private SmartRefreshLayout srf;

    //列表控件
    private RecyclerView rv;

    //背景的数据集合
    private List<TreasureChestInfo.DataBackgroundBean> DataBackgroundsList;

    //套装的数据集合
    private List<TreasureChestInfo.DataFashionBean> DatasList0;

    //帽子的数据集合
    private List<TreasureChestInfo.DataFashionBean> DatasList1;

    //眼镜的数据集合
    private List<TreasureChestInfo.DataFashionBean> DatasList2;

    //颈饰的数据集合
    private List<TreasureChestInfo.DataFashionBean> DatasList3;

    //空视图
    private View emptyView;

    //适配器
    private StTreasuerClothesAdapter adapter;


    //背景适配器
    private StTreasuerBackgroundAdapter bgAdapter;

    //套装按钮
    private ImageView mClothes;

    //帽子按钮
    private ImageView mHat;

    //眼镜按钮
    private ImageView mGlasses;

    //颈饰按钮
    private ImageView mJingshi;

    //背景按钮
    private ImageView mBackground;


    //套装图层
    private ImageView ivClothing;

    //帽子图层
    private ImageView ivHat;

    //眼镜图层
    private ImageView ivGlass;

    //颈饰图层
    private ImageView ivJingshi;

    //保存提交按钮
    private TextView tv_save;

    //提交宠物形象的json数据
    private String saveJson;

    //按钮选中的背景图片集合
    private int[] tabSelectIds = {R.drawable.student_clothes_select, R.drawable.student_hat_select,
            R.drawable.student_glasses_select, R.drawable.student_jingshi_select, R.drawable.student_background_select};

    //按钮未选中的背景图片集合
    private int[] tabUnselectIds = {R.drawable.student_clothes_normal, R.drawable.student_hat_normal,
            R.drawable.student_glasses_normal, R.drawable.student_jingshi_normal, R.drawable.student_background_normal};


    public MyHandler mHandler;

    //使用人的姓名
    private String fromname;
    //使用宠物的姓名
    private String frompetname;


    private static volatile StudentFashionableDressFragment studentFootFragment;

    public static StudentFashionableDressFragment newInstance() {
        studentFootFragment = new StudentFashionableDressFragment();
        return studentFootFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_fashionable_dress;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

        initView(view);
        initData();
        //请求服务器
        http();
    }

    /**
     * 初始化
     */
    private void initData() {
        DataBackgroundsList = new ArrayList<>();
        DatasList0 = new ArrayList<>();
        DatasList1 = new ArrayList<>();
        DatasList2 = new ArrayList<>();
        DatasList3 = new ArrayList<>();
        mHandler = new MyHandler();

        //判断宠物类型
        if ("1".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
            //狗
            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_dog));
        } else if ("2".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
            //猫
            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_cat));
        } else if ("3".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
            //怪物
            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_monster));
        } else if ("4".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
            //熊猫
            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_panda));
        }
    }
    /**
     * 获取百宝箱服装道具接口数据
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "4");
        map.put("platform", "8");
        map.put("acc", AccountUtils.getAccount(getActivity()));
        map.put("role", AccountUtils.getRole(getActivity()));
        map.put("apptoken", AccountUtils.getToken(getActivity()));
        map.put("allboxitem", "1");
        HttpUtils.post(HttpAdress.FEED, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showError();
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    //解析返回服务器返回的JSON数据
                    showContent();
                    TreasureChestInfo info = GsonUtil.jsonToBean(response, TreasureChestInfo.class);

                    Log.i("test", "百宝箱服装：" + response);
                    if ("200".equals(info.getState())) {
                        if (null != info) {

                            if (info.dataFashion_0 != null) {
                                //套装
                                DatasList0 = info.dataFashion_0;
                            }
                            if (info.dataFashion_1 != null) {
                                //帽子
                                DatasList1 = info.dataFashion_1;
                            }
                            if (info.dataFashion_2 != null) {
                                //眼镜
                                DatasList2 = info.dataFashion_2;
                            }
                            if (info.dataFashion_3 != null) {
                                //颈饰
                                DatasList3 = info.dataFashion_3;
                            }
                            if (info.dataBackground != null) {
                                //背景
                                DataBackgroundsList = info.dataBackground;
                            }
                            //设置rv
                            initRv(DatasList0);
                            //设置下拉控件
                            initSrl();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "解析服务器返回数据异常");
                }
            }
        });
    }

    /**
     * 设置下拉刷新控件
     */
    private void initSrl() {
        SrfManager.setSmartByPullListener(srf, null);
    }

    /**
     * 初始化View
     */
    private void initView(View view) {
        srf = view.findViewById(R.id.srf);
        rv = view.findViewById(R.id.rv);

        mClothes = view.findViewById(R.id.iv_fashion_clothes);
        mHat = view.findViewById(R.id.iv_fashion_hat);
        mGlasses = view.findViewById(R.id.iv_fashion_glasses);
        mJingshi = view.findViewById(R.id.iv_fashion_jingshi);
        mBackground = view.findViewById(R.id.iv_fashion_background);

        //套装图层
        ivClothing = view.findViewById(R.id.iv_clothing);
        //帽子图层
        ivHat = view.findViewById(R.id.iv_hat);
        //眼镜图层
        ivGlass = view.findViewById(R.id.iv_glass);
        //颈饰图层
        ivJingshi = view.findViewById(R.id.iv_jingshi);
        //保存按钮
        tv_save = view.findViewById(R.id.tv_save);

        mClothes.setOnClickListener(this);
        mHat.setOnClickListener(this);
        mGlasses.setOnClickListener(this);
        mJingshi.setOnClickListener(this);
        mBackground.setOnClickListener(this);
        tv_save.setOnClickListener(this);
    }


    /**
     * 设置服装列表
     */
    private void initRv(List<TreasureChestInfo.DataFashionBean> datas) {
        emptyView = View.inflate(getContext(), R.layout.base_rv_common_empty_view, null);
        adapter = new StTreasuerClothesAdapter(getContext(), R.layout.student_rv_common_treasure_fashionable,
                datas, mHandler);
        //设置横向的布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 1);
        BqaManager.setRv(emptyView, gridLayoutManager, getContext(), adapter, rv, null);
    }

    /**
     * 设置背景列表
     */
    private void initBgRv() {
        emptyView = View.inflate(getContext(), R.layout.base_rv_common_empty_view, null);
        bgAdapter = new StTreasuerBackgroundAdapter(getContext(), R.layout.student_rv_common_treasure_fashionable,
                DataBackgroundsList);
        //设置横向的布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 1);
        BqaManager.setRv(emptyView, gridLayoutManager, getContext(), bgAdapter, rv, null);
    }

    @Override
    public void onClick(View v) {

        int id = v.getId();
        if (id == R.id.iv_fashion_clothes) {
            //套装按钮
            mClothes.setImageResource(tabSelectIds[0]);
            mHat.setImageResource(tabUnselectIds[1]);
            mGlasses.setImageResource(tabUnselectIds[2]);
            mJingshi.setImageResource(tabUnselectIds[3]);
            mBackground.setImageResource(tabUnselectIds[4]);

            //设置rv
            initRv(DatasList0);
        } else if (id == R.id.iv_fashion_hat) {
            //帽子按钮
            mHat.setImageResource(tabSelectIds[1]);
            mClothes.setImageResource(tabUnselectIds[0]);
            mGlasses.setImageResource(tabUnselectIds[2]);
            mJingshi.setImageResource(tabUnselectIds[3]);
            mBackground.setImageResource(tabUnselectIds[4]);
            //设置rv
            initRv(DatasList1);
        } else if (id == R.id.iv_fashion_glasses) {
            //眼镜按钮
            mHat.setImageResource(tabUnselectIds[1]);
            mClothes.setImageResource(tabUnselectIds[0]);
            mGlasses.setImageResource(tabSelectIds[2]);
            mJingshi.setImageResource(tabUnselectIds[3]);
            mBackground.setImageResource(tabUnselectIds[4]);
            //设置rv
            initRv(DatasList2);
        } else if (id == R.id.iv_fashion_jingshi) {
            //颈饰
            mHat.setImageResource(tabUnselectIds[1]);
            mClothes.setImageResource(tabUnselectIds[0]);
            mGlasses.setImageResource(tabUnselectIds[2]);
            mJingshi.setImageResource(tabSelectIds[3]);
            mBackground.setImageResource(tabUnselectIds[4]);
            //设置rv
            initRv(DatasList3);
        } else if (id == R.id.iv_fashion_background) {
            //背景
            mHat.setImageResource(tabUnselectIds[1]);
            mClothes.setImageResource(tabUnselectIds[0]);
            mGlasses.setImageResource(tabUnselectIds[2]);
            mJingshi.setImageResource(tabUnselectIds[3]);
            mBackground.setImageResource(tabSelectIds[4]);
            //设置rv
            initBgRv();
        } else if (id == R.id.tv_save) {
            //保存宠物形象
            savePetHttp();
        }
    }

    /**
     * 保存宠物形象提交至服务器
     */
    private void savePetHttp() {

        List<SavePetItemJson> list = new ArrayList<>();



        for (int i = 0; i < DatasList0.size(); i++) {
            if (DatasList0.get(i).ischeck) {
                SavePetItemJson data = new SavePetItemJson();
                data.setBoxtype(DatasList0.get(i).getGoods_type() + "");
                data.setBoxitem(DatasList0.get(i).getGoods_id() + "");
                data.setBoxnum("1");
                data.setName(DatasList0.get(i).getName());
                list.add(data);
            }
        }
        for (int i = 0; i < DatasList1.size(); i++) {
            if (DatasList1.get(i).ischeck) {
                SavePetItemJson data = new SavePetItemJson();
                data.setBoxtype(DatasList1.get(i).getGoods_type() + "");
                data.setBoxitem(DatasList1.get(i).getGoods_id() + "");
                data.setBoxnum("1");
                data.setName(DatasList1.get(i).getName());
                list.add(data);
            }
        }

        for (int i = 0; i < DatasList2.size(); i++) {
            if (DatasList2.get(i).ischeck) {
                SavePetItemJson data = new SavePetItemJson();
                data.setBoxtype(DatasList2.get(i).getGoods_type() + "");
                data.setBoxitem(DatasList2.get(i).getGoods_id() + "");
                data.setBoxnum("1");
                data.setName(DatasList2.get(i).getName());
                list.add(data);
            }
        }

        for (int i = 0; i < DatasList3.size(); i++) {
            if (DatasList3.get(i).ischeck) {
                SavePetItemJson data = new SavePetItemJson();
                data.setBoxtype(DatasList3.get(i).getGoods_type() + "");
                data.setBoxitem(DatasList3.get(i).getGoods_id() + "");
                data.setBoxnum("1");
                data.setName(DatasList3.get(i).getName());
                list.add(data);
            }
        }

        for (int i = 0; i < DataBackgroundsList.size(); i++) {
            if (DataBackgroundsList.get(i).ischeck) {
                SavePetItemJson data = new SavePetItemJson();
                data.setBoxtype(DataBackgroundsList.get(i).getGoods_type() + "");
                data.setBoxitem(DataBackgroundsList.get(i).getGoods_id() + "");
                data.setBoxnum("1");
                data.setName(DataBackgroundsList.get(i).getName());
                list.add(data);
            }
        }

        if (list.size() == 0) {
            UiUtils.Toast("请选择服装道具后再保存", false);
            return;
        }

        saveJson = GsonUtil.listToJson(list);

        Log.i("test", "保存宠物形象" + saveJson);
        String acc = SPUtil.getString(getActivity(), SpKeys.ACCOUNT);
        String token = SPUtil.getString(getActivity(),SpKeys.TOKEN1);
        String name = SPUtil.getString(getActivity(),SpKeys.NAME);
        String petname = SPUtil.getString(getActivity(),SpKeys.PETNAME);

        Map<String, String> map = new HashMap<>();
        map.put("type", "5");
        map.put("platform", "8");
        map.put("acc", acc);
        map.put("role", "0");
        map.put("apptoken", token);
        map.put("toacc", acc);
        map.put("torole", "0");
        map.put("fromname", name);
        map.put("frompetname", petname);
        map.put("toname", name);
        map.put("frompetname", petname);

        map.put("jsitem", saveJson);

        HttpUtils.post(HttpAdress.FEED, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {

                showError();
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    //解析返回服务器返回的JSON数据
                    showContent();
                    TreasureChestInfo info = GsonUtil.jsonToBean(response, TreasureChestInfo.class);

                    Log.i("test", "保存宠物形象" + response);
                    if ("200".equals(info.getState())) {
                        UiUtils.Toast("形象保存成功", false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "解析服务器返回数据异常");

                }
            }
        });
    }


    /**
     * Handler回调设置宠物形象
     */
    public class MyHandler extends Handler {
        public Bundle bundle = new Bundle();

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //套装（底图）
                case 0:
                    bundle = msg.getData();
                    String data0 = bundle.getString("url");
//                    UiUtils.Toast("0" + ",data:" + data0, false);
                    if ("-1".equals(data0)) {
                        //判断宠物类型
                        if ("1".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //狗
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_dog));
                        } else if ("2".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //猫
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_cat));
                        } else if ("3".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //怪物
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_monster));
                        } else if ("4".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //熊猫
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_panda));
                        }


                    } else {
                        Glide.with(getActivity()).load(data0).into(ivClothing);
                        ivHat.setImageDrawable(getResources().getDrawable(R.color.transparent));
                        ivGlass.setImageDrawable(getResources().getDrawable(R.color.transparent));
                        ivJingshi.setImageDrawable(getResources().getDrawable(R.color.transparent));

                        for (int i = 0; i < DatasList1.size(); i++) {
                            DatasList1.get(i).ischeck = false;
                        }
                        for (int i = 0; i < DatasList2.size(); i++) {
                            DatasList2.get(i).ischeck = false;
                        }
                        for (int i = 0; i < DatasList3.size(); i++) {
                            DatasList3.get(i).ischeck = false;
                        }
                    }

                    break;
                //帽子
                case 1:
                    bundle = msg.getData();
                    String data1 = bundle.getString("url");
//                    UiUtils.Toast("1" + ",data:" + data1, false);

                    if ("-1".equals(data1)) {
                        ivHat.setImageDrawable(getResources().getDrawable(R.color.transparent));
                    } else {
                        Glide.with(getActivity()).load(data1).into(ivHat);

                        //判断宠物类型
                        if ("1".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //狗
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_dog));
                        } else if ("2".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //猫
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_cat));
                        } else if ("3".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //怪物
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_monster));
                        } else if ("4".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //熊猫
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_panda));
                        }

                        for (int i = 0; i < DatasList0.size(); i++) {
                            DatasList0.get(i).ischeck = false;
                        }
                    }

                    break;
                //眼镜
                case 2:
                    bundle = msg.getData();
                    String data2 = bundle.getString("url");
//                    UiUtils.Toast("2" + ",data:" + data2, false);
                    if ("-1".equals(data2)) {
                        ivGlass.setImageDrawable(getResources().getDrawable(R.color.transparent));
                    } else {
                        Glide.with(getActivity()).load(data2).into(ivGlass);
                        //判断宠物类型
                        if ("1".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //狗
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_dog));
                        } else if ("2".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //猫
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_cat));
                        } else if ("3".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //怪物
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_monster));
                        } else if ("4".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //熊猫
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_panda));
                        }
                        for (int i = 0; i < DatasList0.size(); i++) {
                            DatasList0.get(i).ischeck = false;
                        }
                    }
                    break;
                //颈饰
                case 3:
                    bundle = msg.getData();
                    String data3 = bundle.getString("url");
//                    UiUtils.Toast("3" + ",data:" + data3, false);
                    if ("-1".equals(data3)) {
                        ivJingshi.setImageDrawable(getResources().getDrawable(R.color.transparent));
                    } else {
                        Glide.with(getActivity()).load(data3).into(ivJingshi);
                        //判断宠物类型
                        if ("1".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //狗
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_dog));
                        } else if ("2".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //猫
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_cat));
                        } else if ("3".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //怪物
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_monster));
                        } else if ("4".equals(SPUtil.getString(getActivity(),SpKeys.SERVICEPETTYPE))) {
                            //熊猫
                            ivClothing.setImageDrawable(getResources().getDrawable(R.drawable.stu_pet_panda));
                        }
                        for (int i = 0; i < DatasList0.size(); i++) {
                            DatasList0.get(i).ischeck = false;
                        }
                    }
                    break;
            }
        }
    }
}
